import { Hero } from '../hero';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { HeroService } from '../hero.service';
import { MessageService } from '../../message.service';

@Component({
  selector: 'app-heroe-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

  // 选中的英雄
  selectedId = 0;

  // onSelect(hero: Hero): void{
  //    this.selectedHero = hero
  //     /**
  //      * 在字符串中传递参数时，有两个注意点:
  //      * 1.需要用反单引号，这样才能识别参数
  //      * 2.用${}来传递，和mybatis类似，只不过用$，可能是为了区分
  //      * */
  //    this.messageService.add(`HeroesComponent：Selected Hero Id = ${hero.id}`)
  // }



  // 英雄数组
  heroes: Hero[]= []

  getHeroes(){

    this.selectedId = Number(this.route.snapshot.paramMap.get('id'))
     // 在订阅时subscribe里面的回调函数连函数的()都可以不用写
     this.heroService.getHeroes().subscribe(

        heroes => this.heroes = heroes
     )
  }

  add(name:string): void{
     // 先去掉空格，若为空，则本来就为空
     name = name.trim()
     if(!name) return
     this.heroService.addHero({name} as Hero)
      .subscribe(hero => this.heroes.push(hero))
  }

  deleteHero(hero: Hero): void{
     this.heroes = this.heroes.filter(h => h !== hero)
     this.heroService.deleteHero(hero).subscribe()
  }

  constructor(private heroService: HeroService, private route: ActivatedRoute) { }

  ngOnInit(): void {
     this.getHeroes()
  }

}


